package cn.bluech.lib.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * cvs文件(Excel表格文件)
 * 目前只实现了写操作
 */
public class CsvFile {
    private File file;
    private BufferedWriter writer;

    private CsvFile(){
        file = null;
        writer = null;
    }

//    public CsvFile(String filePath){
//        // 这里如果存在应该是读取这个文件
//        open(filePath);
//    }

    public static CsvFile create(String filePath){
        CsvFile csvFile = new CsvFile();
        try {
            csvFile.file = new File(filePath);
            if(csvFile.file.exists())
                csvFile.file.delete();
            csvFile.file.createNewFile();

            FileOutputStream os = new FileOutputStream(csvFile.file);
            csvFile.writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"), 1024);
            byte[] utf8Head = {(byte)0xEF,(byte)0xBB,(byte)0xBF};
            os.write(utf8Head);
        } catch (IOException e) {
            StreamUtils.close(csvFile.writer);
            return null;
        }

        return csvFile;
    }

    public boolean isOpen(){
        return writer!=null;
    }

    public void flush(){
        try {
            writer.flush();
        } catch (IOException ignored) {
        }
    }

    public void close(){
        StreamUtils.close(writer);
        writer = null;
    }

    public boolean writeLine(Line line){
        if(null==writer)
            return false;

        try {
            writer.write(line.toString());
            writer.write('\n');
        } catch (IOException e) {
            return false;
        }

        return true;
    }


    public static final class Line{
        private final StringBuilder line = new StringBuilder();

        public Line add(String value){
            // todo: 这里应该对','进行转义(存在','会用双引号将项包起来，双引号又会做转换，这里暂不处理)
            if(line.length()>0)
                line.append(',');
            line.append(value);

            return this;
        }

        public Line skip(int count){
            while(count-->0)
                line.append(',');

            return this;
        }

//        public void clean(){
//
//        }

        @Override
        public String toString() {
            return line.toString();
        }
    }
}
